package com.admin.config;

import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.MyDataCenterInstanceConfig;
import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EurekaConfigProcessor implements ConfigProcessor {

    // 创建日志对象
    private static final Logger log = LoggerFactory.getLogger(EurekaConfigProcessor.class);

    private ApplicationInfoManager applicationInfoManager;
    private EurekaClient eurekaClient;

    @Override
    public void process() {
        // 输出日志，表示开始处理Eureka配置
        log.info("启用Eureka");
        // 初始化ApplicationInfoManager
        initializeApplicationInfoManager();
        // 初始化EurekaClient
        initializeEurekaClient();
        // 设置服务状态为UP，表示服务可用
        applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP);
        // 输出日志，表示服务已经成功注册到Eureka
        log.info("服务已注册至Eureka");
    }

    // 初始化ApplicationInfoManager的方法
    private void initializeApplicationInfoManager() {
        if (applicationInfoManager == null) {
            // 创建Eureka实例配置
            EurekaInstanceConfig instanceConfig = new MyDataCenterInstanceConfig();
            // 根据配置创建InstanceInfo
            InstanceInfo instanceInfo = new EurekaConfigBasedInstanceInfoProvider(instanceConfig).get();
            // 使用InstanceConfig和InstanceInfo初始化ApplicationInfoManager
            applicationInfoManager = new ApplicationInfoManager(instanceConfig, instanceInfo);
        }
    }

    // 初始化EurekaClient的方法
    private void initializeEurekaClient() {
        if (eurekaClient == null) {
            // 创建Eureka客户端配置
            EurekaClientConfig clientConfig = new DefaultEurekaClientConfig();
            // 使用ApplicationInfoManager和ClientConfig初始化EurekaClient
            eurekaClient = new DiscoveryClient(applicationInfoManager, clientConfig);
        }
    }

    // 关闭Eureka客户端，释放资源
    public void shutdown() {
        if (eurekaClient != null) {
            // 关闭Eureka客户端
            eurekaClient.shutdown();
            // 输出日志，表示Eureka客户端已关闭
            log.info("Eureka客户端已关闭");
        }
    }
}
